<?php
namespace App\WebSocket\Controller;

use App\Storage\ChatAutoReplyCache;
use App\Storage\Emoji;
use App\Task\RoomTask;
use App\WebSocket\Actions\Room\RoomMessage;
use App\WebSocket\Actions\Room\RoomServer;
use EasySwoole\EasySwoole\Swoole\Task\TaskManager;
use EasySwoole\Socket\AbstractInterface\Controller;
use EasySwoole\Socket\Client\WebSocket;

class Room extends Controller {

    /**
     * 客服-用户之间的消息互通
     */
    function roomBroadcast() {

        /** @var WebSocket $client */
        $client = $this->caller()->getClient();
        $broadcastPayload = $this->caller()->getArgs();
        if (!empty($broadcastPayload) && isset($broadcastPayload['content'])) {
            $allEmoji = Emoji::getInstance()->getEmoji();
            foreach($allEmoji as $_k => $_v){ // 处理表情包
                $broadcastPayload['content'] = str_replace($_k,$_v,$broadcastPayload['content']);
            }
            $message = new RoomMessage();
            $message->setFromUserFd($client->getFd());
            $message->setContent($broadcastPayload['content']);
            $message->setType($broadcastPayload['type']);
            $message->setSendTime(date('Y-m-d H:i:s'));
            TaskManager::async(new RoomTask([
                'payload' => $message->__toString(),
                'content' => $broadcastPayload['content'],
                'fromFd' => $client->getFd(),
                'shopId' => $broadcastPayload['shopId'],
                'userId' => $broadcastPayload['userId'],
                'isShop' => $broadcastPayload['isShop'],
                'toUserId' => $broadcastPayload['toUserId'],
                'type'  => $broadcastPayload['type'],
            ]));
            //自动回复拦截
            $autoReply = ChatAutoReplyCache::getInstance($broadcastPayload['shopId'])->get($broadcastPayload['shopId']);
            if ($autoReply) {
                foreach ($autoReply as $reply) {
                    if (strpos($broadcastPayload['content'], $reply['keyword']) !== false) {
                        // 发送方要改成系统
                        $roomServerMessage = new RoomServer();
                        $roomServerMessage->setContent($reply['content']);

                        TaskManager::async(new RoomTask([
                            'payload' => $roomServerMessage->__toString(),
                            'content' => $reply['content'],
                            'fromFd' => $client->getFd(),
                            'shopId' => $broadcastPayload['shopId'],
                            'userId' => $broadcastPayload['userId'],
                            'isShop' => $broadcastPayload['isShop'],
                            'toUserId' => $broadcastPayload['toUserId'],
                            'type'  => $broadcastPayload['type'],
                        ]));
                    }
                }
            }
        }
        $this->response()->setStatus($this->response()::STATUS_OK);
    }

}